import { useEffect, useState } from 'react'
import { Upload } from 'antd';
import { UploadFile } from 'antd/es/upload/interface'
import { UploadRequestOption } from 'rc-upload/es/interface'
import { getClientSts } from '@/api'
import COS from 'cos-js-sdk-v5';
import { md5 } from '@/utils'
import { InboxOutlined } from '@ant-design/icons';

import './upload.scss'

let cos: COS = null

export default function UploadPage () {
  const [fileList, setFileList] = useState<UploadFile[]>([])
  const [hashNameList, setHashNameList] = useState<string[]>([])

  useEffect(() => {
    getClientSts().then(res => {
      cos = new COS({
        SecretId: res.Credentials.TmpSecretId,
        SecretKey: res.Credentials.TmpSecretKey,
        SecurityToken: res.Credentials.Token
      })
    })
  }, [])

  async function onUpload (e: UploadRequestOption) {
    const file = e.file as File
    const hash = await md5(file)
    setHashNameList([...hashNameList, hash + file.name.split('.').pop()])
    await cos.uploadFile({
      Bucket: 'static-1302789012', // 填入您自己的存储桶，必须字段
      Region: 'ap-shanghai', // 存储桶所在地域，例如ap-beijing，必须字段
      // 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段
      Key: `temp/${hash}.${file.name.split('.').pop()}`,
      // 每个分片 100MB
      SliceSize: 1024 * 1024 * 100,
      Body: file,
      onProgress ({ percent }) {
        e.onProgress({ percent: percent * 100 })
      }
    })
    e.onSuccess({})
  }

  return <>
    <Upload.Dragger
      className="upload-page-upload-component"
      multiple
      fileList={fileList}
      customRequest={onUpload}
      accept="image/*"
      onChange={e => setFileList(e.fileList)}
    >
      <p className="ant-upload-drag-icon">
        <InboxOutlined />
      </p>
      <p className="ant-upload-text">拖拽上传</p>
      <p className="ant-upload-hint">
        Support for a single or bulk upload. Strictly prohibited from uploading company data or other
        banned files.
      </p>
    </Upload.Dragger>
    {hashNameList.map(item => <div key={item}>{item}</div>)}
  </>
}
